package com.vpen.account.demo.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vpen.clib.constant.CConstant;
import com.vpen.clib.result.CResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/7/18 15:30
 */
@Slf4j
@RestControllerAdvice
@AllArgsConstructor(onConstructor_ = @Autowired)
public class AccountExceptionHandler {


    private final ObjectMapper objectMapper;

    private final HttpServletResponse response;


    /**
     * sql异常
     */
    @ExceptionHandler({SQLException.class})
    public void duplicateException(SQLException exception) {
        writeException(exception);
    }


    /**
     * 参数校验异常
     */
    @ExceptionHandler({BindException.class})
    public void validException(BindException exception) {
        String message = exception.getAllErrors().get(0).getDefaultMessage();
        writeException(exception);
    }

    @ExceptionHandler({AccountDemoException.class})
    public void accountException(AccountDemoException exception) {
        writeException(exception);
    }

    @ExceptionHandler({HttpMessageNotReadableException.class})
    public void handleHttpMessageNotReadable(HttpMessageNotReadableException exception) {
        writeException(exception);
    }


    public void writeException(Exception exception) {
        //设置返回请求头
        PrintWriter out = null;
        try {
            response.setContentType(CConstant.CONTENT_TYPE);
            //写出流
            out = response.getWriter();
            CResult<String> result = CResult.error();
            result.setMsg(exception.getMessage());
            out.write(objectMapper.writeValueAsString(result));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }
}
